package net.caixiaomi.info.shopkeeper;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import net.caixiaomi.info.R;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.util.FileHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mac on 2018/11/15.
 */

public class ImgScanActivity extends BaseActivity {
    private ImgViewPager mViewPager;
    private String[] imageIds;
    public static final String KEY_IMAGE_ID = "imageId";
    public static final String KEY_IMAGE_EDITE = "edite";
    private TextView txtIndex;
    private int mTargetId;
    private ViewGroup.LayoutParams lp;
    private List<PhotoView> mViews=new ArrayList<PhotoView>();
    public static int edite=0;

    @Override
    protected int layout() {
        return R.layout.image_scan_layout;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_image_scan);
        lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        orignDefBmp = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_add);
        mViewPager = (ImgViewPager) findViewById(R.id.vp);
        txtIndex = (TextView) findViewById(R.id.index);
        mEdite = (TextView) findViewById(R.id.img_scan_edite);
        mEdite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                //发送广播
//				Intent mIntent = new Intent(lCanEdite);
                edite=lCanEdite;
//				sendBroadcast(mIntent);
                finish();
            }
        });

        showImages();
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                txtIndex.setText((arg0 + 1) + "/" + imageIds.length);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    private void showImages() {
        // TODO Auto-generated method stub
        Intent mIntent = getIntent();
        imageIds = mIntent.getStringArrayExtra(KEY_IMAGE_ID);
        mTargetId = mIntent.getIntExtra("targetid", 0);
        lCanEdite = mIntent.getIntExtra("edite", 0);
        if(lCanEdite!=0){
            mEdite.setVisibility(View.VISIBLE);
        }else{
            mEdite.setVisibility(View.GONE);
        }
        if (imageIds != null && imageIds.length > 0) {
            int lIndex=mTargetId+1;
            txtIndex.setText(lIndex+"/"+ imageIds.length);

            inflateVp(imageIds);
//			mViewPager.setAdapter(new SamplePagerAdapter());
        } else {
            finish();
        }
    }

    private void inflateVp(final String[] imageIds) {
        PhotoView iv=null;
        for (int i = 0; i < imageIds.length; i++) {
            iv=new PhotoView(this);
            iv.setLayoutParams(lp);
            mViews.add(iv);
        }
        mViewPager.setAdapter(new SamplePagerAdapter());
        mViewPager.setCurrentItem(mTargetId);
    }
    class SamplePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mViews.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            // TODO Auto-generated method stub
            final PhotoView photoView = mViews.get(position);
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);

            if (imageIds[position].equals("")) {
                Bitmap photo=null;
                Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "cxm"+ ".jpg"));

                if (uri != null) {
                    photo = BitmapFactory.decodeFile(uri.getPath());
                }

                FileOutputStream fileOutputStream = null;
                File file=FileHelper.getOutputMediaFile();
                // 打开文件输出流
                try {
                    fileOutputStream = new FileOutputStream(file);
                    // 生成图片文件
                    photo.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    // 相片的完整路径
                    Glide.with(ImgScanActivity.this).load(photo).into(photoView);

                //加载图片
//                Glide.with(ImgScanActivity.this).load(imageIds[position]).into(photoView);

            }catch (FileNotFoundException e) {
                    e.printStackTrace();
                }}else{

                Glide.with(ImgScanActivity.this).load(imageIds[position]).into(photoView);
            }
            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView((View) object);
        }
    }

//    ImageLoader imageLoader = ImageLoader.getInstance();
//    DisplayImageOptions options = new DisplayImageOptions.Builder()
//            .showImageForEmptyUri(R.drawable.auto_img)
//            .showImageOnFail(R.drawable.auto_img).cacheInMemory(true)
//            .cacheOnDisk(true).considerExifParams(true).build();

    private Handler mHandler=new Handler();
    private Bitmap orignDefBmp;
    private TextView mEdite;
    private int lCanEdite;

//    public Bitmap loadImageFromUrl(String url) throws Exception  {
//        final DefaultHttpClient client = new DefaultHttpClient();
//        final HttpGet getRequest = new HttpGet(url);
//
//        HttpResponse response = client.execute(getRequest);
//        int statusCode = response.getStatusLine().getStatusCode();
//        if (statusCode != HttpStatus.SC_OK)  {
//            Log.e("PicShow", "Request URL failed, error code =" + statusCode);
//        }
//
//        HttpEntity entity = response.getEntity();
//        if (entity == null) {
//            Log.e("PicShow", "HttpEntity is null");
//        }
//        InputStream is = null;
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        try {
//            is = entity.getContent();
//            byte[] buf = new byte[1024];
//            int readBytes = -1;
//            while ((readBytes = is.read(buf)) != -1) {
//                baos.write(buf, 0, readBytes);
//            }
//        } finally {
//            if (baos != null) {
//                baos.close();
//            }
//            if (is != null) {
//                is.close();
//            }
//        }
//        byte[] imageArray = baos.toByteArray();
//        return BitmapFactory.decodeByteArray(
//                imageArray, 0, imageArray.length);
//    }
}
